<!-- ZhanjiangMap.vue -->
<template>
  <div id="map" class="map-container"></div>
</template>

<script setup>
import { onMounted, onBeforeUnmount } from 'vue';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { monitorApi } from '@/api';

let mapInstance = null;

onMounted(async () => {
  const map = L.map('map', {
    center: [21.2707, 110.3589], // 湛江中心坐标
    zoom: 10,
    attributionControl: false // 去掉 OpenStreetMap 标识
  });
  
  // 保存地图实例引用
  mapInstance = map;

  // 天地图图层（影像底图）
  const imgLayer = L.tileLayer(
    'https://t{s}.tianditu.gov.cn/img_w/wmts?' +
      'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&' +
      'STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&' +
      'TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=3e310b3dc267170e50b4277a166e7bbb',
    {
      subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
      maxZoom: 18,
    }
  );

  // 天地图图层（标注层）
  const labelLayer = L.tileLayer(
    'https://t{s}.tianditu.gov.cn/cia_w/wmts?' +
      'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&' +
      'STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&' +
      'TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=3e310b3dc267170e50b4277a166e7bbb',
    {
      subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
      maxZoom: 18,
    }
  );

  // 添加图层
  const layerGroup = L.layerGroup([imgLayer, labelLayer]).addTo(map);

  // 获取点位数据
  try {
    const res = await monitorApi.getEnvironmentDataList({});
    if (res.code === 200 && Array.isArray(res.data)) {
      res.data.forEach(item => {
        if (item.latitude && item.longitude) {
          const marker = L.marker([item.latitude, item.longitude]).addTo(map);
          marker.bindPopup(item.name || '监控点');
        }
      });
    }
  } catch (error) {
    console.error('获取环境监测数据失败:', error);
  }
});

onBeforeUnmount(() => {
  // 清理地图实例以防止内存泄漏
  if (mapInstance) {
    mapInstance.remove();
    mapInstance = null;
  }
});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  border-radius: 8px;
  overflow: hidden;
}
</style>
